package com.yuanhua.sim.netty.serve.handler;

import com.yuanhua.sim.netty.decoder.MyDecoder;
import com.yuanhua.sim.netty.decoder.MyEncoder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Service;

/**
 * @author yuanhua
 */
@Service
@ChannelHandler.Sharable
public class MyNettySocketChannelHandler extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //1.拆包器
        ch.pipeline()
                //读空闲 每隔二十秒 调用一次 userEventTriggered
                .addLast(new IdleStateHandler(20, 0,0))
                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 5, 4))
                //2.自定义解码器
                .addLast(new MyDecoder())
                //http编解码
                //.addLast("http-codec", new HttpServerCodec())
//                .addLast("protocolHandler",new WebSocketServerProtocolHandler("/websocket"))
                //3.自定义业务
                .addLast(new ServerChatHandler())
                .addLast(new LoginReqHandler())
                .addLast(new MsgReqHandler())
                .addLast(new PingReqHandler())
                //4.自定义编码器
                .addLast(new MyEncoder())
                //异常兜底
                .addLast(ExceptionHandler.INSTANCE);
    }
}
